﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data;
using Data.implement;
using log4net;
using Services.Interface;

namespace Services.Implement
{
    public class ChargingService:IChargingService
    {
        private IUserRepositery userRepositery;
        private IChargingRecordRepositery chargingRecordRepositery;

        private ILog Logger;
   

        public ChargingService()
        {
            Logger = LogManager.GetLogger(this.GetType());
            userRepositery = DataRepositeryManagerFactory.CreateUserRepositery();
            chargingRecordRepositery = DataRepositeryManagerFactory.CreateChargingRecordRepositery();
        }

        public User GetUserByGUID(string GUID)
        {
            return userRepositery.GetUserByGuid(GUID);
        }

        public ChargingResultEnum Charging(WeiXinUser weixinUser,int targetId)
        {
            try
            {
                User user = null;

                if (IsExistNumber(weixinUser, out user))
                {
                    if (user.LimitTimes<int.Parse(ConfigurationSettings.AppSettings["LimitTimes"].Trim()))
                    {
                        if (chargingRecordRepositery.InsertRecord(user.UserId, targetId))
                        {
                            userRepositery.AddChargingTime(user.UserId, targetId);
                            return ChargingResultEnum.Successful;
                        }
                        else
                        {
                            return ChargingResultEnum.HaveCharging;
                        }
                    }
                    else
                    {
                        return ChargingResultEnum.OverLimitTimes;
                    }
                    
                    
                }
                else
                {
                    return ChargingResultEnum.AccountAuthFail;
                }
                
                
                
            }
            catch (Exception e)
            {
                Logger.Error("ChargingService-Charging has an error:" + e + "./n/rThe user is " + weixinUser.openId + " /n/r" + weixinUser.nickname + " /n/r" + weixinUser.sex + " /n/r" + weixinUser.country + " /n/r" + weixinUser.province + " /n/r" + weixinUser.city + " /n/r" + weixinUser.headimgurl);
                return ChargingResultEnum.Exceptions;
            }
            
            
        }

        

         private bool IsExistNumber(WeiXinUser weixinUser, out User user)
        {
            user = userRepositery.GetOrInsertUser(weixinUser);
             return true;
        }

        
    }
}
